<?php	
	defined('_JEXEC') or die('Restricted access');
	//
    require_once("user_agent_class.php");
    //
	// t_log
	//
	class t_log
	{
        // constants
        // M
        const msg_type_normal = 1;
        const msg_type_error = 1;
		// properties
        // private
        // E
		private  $_error_count = 0;
		// L
		private  $_log_error_filter_array = array("MySQL server has gone away");
		// properties
        // public
        //
        
        // P
		public $report_log = '';
        // Q
        public $query_parameter = null; //t_query_parameter
        // S
		public $save_error_to_db = false;
        public $show_on_page = false;
        
        // U
        public $user_agent = false; //t_user_agent_component
        
        // method declaration
        // private
		// I
		private function _is_error_log_to_filter($a_error)
		{
			
			$local_return = false;
			foreach ($this->_log_error_filter_array As $local_filter_string)
			{
				if (strpos(strtoupper($a_error),strtoupper($local_filter_string)) !== false)
				{
					$local_return = true;
					break;
					
				}
			}
			return $local_return;
		}
		// S
		private function send_log_by_email ($a_msg_type,$a_msg,$a_url,$a_lno,$a_stack,$a_from = "error_log@cuteengine.com")
		{
            
		
		  global $g_cuteengine;
          try
		  {
            //
            $local_message = date( "d/m/Y H.i.s ", time() )."
                browser :".$this->user_agent->browser."
                browser_version: ".$this->user_agent->browser_version."
                $a_msg 
                Message Type:$a_msg_type 
                Page: $a_url 
                Row No: $a_lno 
                Stack: $a_stack";
            
            if ($g_cuteengine->error_message_sent < $g_cuteengine->max_error_message_sent)
            {
                $g_cuteengine->error_message_sent++;
                mail('cristian.rustichelli@gmail.com', 'Error Workly n°'.$g_cuteengine->error_message_sent.' '.date( "d/m/Y H.i.s ", time() ),$local_message,"From: ".$a_from);
            }
		  }
		  catch(Exception $e)
          {	
			$e->getMessage = "send_log_by_email Exception: ".$e->getMessage;
            $this->add_log_on_page($e->getMessage);
		  }
		}
        private function send_log_into_database($a_msg_type,$a_msg,$a_url,$a_lno,$a_stack)
		{
            global $g_ambient_namespace;
			if ((! isset($this->query_parameter)) && (isset($g_ambient_namespace)))
                $this->query_parameter = new t_query_parameter('',$g_ambient_namespace->connection);
            if ((! isset($this->query_parameter)) && ($this->save_error_to_db))
            {
                $sSQL = "INSERT INTO `logs` (`logsID` ,`logsData` ,`logsBrowser` ,`logsVersioneBrowser` ,`logsMessaggio`,".
                    "`logsMsgType` ,`logsUrl` ,`logsLno` ,`logsStack`)".
                    "VALUES (NULL , NOW(), '".$this->user_agent->browser."', '".$this->user_agent->browser_version."', '$a_msg',".
                    "$a_msg_type ,'$a_url' ,$a_lno ,'$a_stack')";
                echo $sSQL;
                $this->query_parameter->sql_str = $sSQL;
                if (! $this->query_parameter->execute_query(true,true))
				{
					$local_error = "add_log_error QUERY ERROR: ".mysqli_errno($this->query_parameter).": ".mysqli_error($this->query_parameter)." when executing:'$sSQL'";
                    //$this->add_log_error($local_error);
                    $this->prepare_log($local_error,debug_backtrace(),
                        $local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
                    $this->send_log_by_email($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
				}
            }
            else
            {
                //$this->add_log_on_page("TYPE: $a_msg_type - LOG: '$a_msg' - URL: '$a_url' - LNO: '$a_lno' - STACK: '$a_stack'");   
            }  
		
		}
        // method declaration
        // public
        public function __construct() 
		{		
            global $g_ambient_namespace;
            if (isset($g_ambient_namespace))
            {
                $this->user_agent = $g_ambient_namespace->user_agent; 
            }    
            else 
            {
                $this->user_agent = new t_user_agent_component;
            }    
            //
            
        }
		// A
		public function add_log_as_email($a_log,$a_debug_backtrace = NULL)
		{
		  try
		  {
            //echo "add_log_normal: $a_log";
			$this->prepare_log($a_log,$a_debug_backtrace,
                $local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
            $this->send_log_by_email($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack,"normal_log@cuteengine.com");
           // $this->send_log_into_database($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
		  }
		  catch(Exception $e)
          {	
			$e->getMessage = "add_log_error Exception: ".$e->getMessage;
			$this->prepare_log($e,null,
                $local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
            $this->send_log_by_email($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
		  }
		}        
        
		public function add_log_error($a_log,$a_debug_backtrace = NULL,$a_add_to_report_log = true)
		{
		 // global $g_ambient_namespace;
		  try
		  {
            
			//echo "add_log_error: $a_log";
			$this->prepare_log($a_log,$a_debug_backtrace,
                $local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
				$local_msg = "Page: " . $_SERVER['REQUEST_URI']." 
				" .$local_msg;               
			if ($this->_is_error_log_to_filter($local_msg))
			{
				$local_msg = strpos(strtoupper($local_msg),strtoupper("MySQL server has gone away"))." - ANNNULLLLLLLLAAAAAAAAAAAATTTTTTTTTTTTTTOOOOO! $local_msg";
				//$g_ambient_namespace->log->add_a_report_log("ANNNULLLLLLLLAAAAAAAAAAAATTTTTTTTTTTTTTOOOOO");
				return;
			}
			else
			{
				$local_msg = strpos(strtoupper($local_msg),strtoupper("MySQL server has gone away"))." - NON ANNNULLLLLLLLAAAAAAAAAAAATTTTTTTTTTTTTTOOOOO! $local_msg";
				//$g_ambient_namespace->log->add_a_report_log("NON ANNNULLLLLLLLAAAAAAAAAAAATTTTTTTTTTTTTTOOOOO");
			}
			//
	        if ($a_add_to_report_log === true)
            {
                $this->add_a_report_log("ERRORE!!!!!: $local_msg");
            }
            $this->_error_count ++;
            //$this->send_log_by_email($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
            $this->send_log_into_database($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
		  }
		  catch(Exception $e)
          {	
			$e->getMessage = "add_log_error Exception: ".$e->getMessage;
			$this->prepare_log($e,null,
                $local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
            $this->send_log_by_email($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
		  }
		}
		public function add_log_normal($a_log,$a_debug_backtrace = NULL)
		{
		  try
		  {
            //echo "add_log_normal: $a_log";
			//$this->prepare_log($a_log,$a_debug_backtrace,
              //  $local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
            //$this->send_log_by_email($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack,"normal_log@cuteengine.com");
           // $this->send_log_into_database($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
		  }
		  catch(Exception $e)
          {	
			$e->getMessage = "add_log_error Exception: ".$e->getMessage;
			$this->prepare_log($e,null,
                $local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
            $this->send_log_by_email($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
		  }
		}
		
        public function add_log_from_javascript ($a_msg_type,$a_msg,$a_url,$a_lno,$a_stack)
		{
		  try
		  {
 	        $this->send_log_by_email($a_msg_type,$a_msg,$a_url,$a_lno,$a_stack);
            $this->send_log_into_database($a_msg_type,$a_msg,$a_url,$a_lno,$a_stack);
            $sSQL = "INSERT INTO `logs` (`logsID` ,`logsData` ,`logsBrowser` ,`logsVersioneBrowser` ,`logsMessaggio`,".
                "`logsMsgType` ,`logsUrl` ,`logsLno` ,`logsStack`)".
                "VALUES (NULL , NOW(), '".c_current_browser_type."', '".c_current_browser_version."', '$msg',".
                "$msg_type ,'$url' ,$lno ,'$stack')";
		  }
		  catch(Exception $e)
          {	
			$e->getMessage = "add_log_error Exception: ".$e->getMessage;
			$this->prepare_log($e,null,
                $local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
            $this->send_log_by_email($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
		  }            
		}
        public function add_log_on_page($a_log,$a_add_to_report_log = false)
		{
            //echo "this->show_on_page: ". $this->show_on_page. "<br>";
            if ($a_add_to_report_log === true)
            {
                $this->add_a_report_log($a_log);
            }
			
            if ($this->show_on_page === true)
            {
                echo $a_log . " - " . date( "d/m/Y H.i.s ", time() ) ."<br>";
            }
            
        }
        public function add_a_report_log($a_log)
		{
            //echo $a_log;
			$this->report_log .= date( "d/m/Y H.i.s ", time() ) . ": ". $a_log . "\n";           
        }	
        // E
        function error_count()
        {
            return $this->_error_count;
        }        
        // I
        public function initialize_javascript_function()
		{
            global $g_javascript_namespace;
            if (isset($g_javascript_namespace))
            {
                //echo "g_javascript_namespace OK";
                //$local_function_body = 'return ""';
                $local_function_body = " 
        try
        {
            ";
				if ($this->browser = t_user_agent_component::t_browser_fox)
				{
					$local_function_body .=	"if (a_e != undefined)
					return a_e.stack;
				else	
					try {(0)()} catch (e) 
					{
						return e.stack.replace(/^.*?\\n/,'').
							replace(/(?:\\n@:0)?\s+$/m,'').
							replace(/^\(/gm,'{anonymous}(');
					}
            ";
				}
				else if ($this->browser = t_user_agent_component::t_browser_op)	
				{
                    
					$local_function_body .=	"try {(0)()} catch (e) 
				{
					if (a_e != undefined)
						local_e = a_e;
					else
						local_e = e;
					var lines = local_e.message.split(\"\\n\"),
						ANON = '{anonymous}',
						lineRE = /Line\s+(\d+).*?in\s+(http\S+)(?:.*?in\s+function\s+(\S+))?/i,
						i,j,len;

					for (i=4,j=0,len=lines.length; i<len; i+=2) 
					{
						if (lineRE.test(lines[i])) 
						{
							lines[j++] = (RegExp.$3 ?
								RegExp.$3 + '()@' + RegExp.$2 + RegExp.$1 :
								ANON + RegExp.$2 + ':' + RegExp.$1) +
								' -- ' + lines[i+1].replace(/^\s+/,'');
						}
					}

					lines.splice(j,lines.length-j);
					return lines;
				}
			";
				}
				else
				{
					$local_function_body .=	"var curr  = arguments.callee.caller,
					FUNC  = 'function', ANON = \"{anonymous}\",
					fnRE  = /function\s*([\w\-$]+)?\s*\(/i,
					stack = [],j=0,
					fn,args,i;

				while (curr) 
				{
					fn    = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON;
					args  = stack.slice.call(curr.arguments);
					i     = args.length;

					while (i--) 
					{
						switch (typeof args[i]) 
						{
							case 'string'  : args[i] = '\"'+args[i].replace(/\"/g,'\\\"')+'\"'; break;
							case 'function': args[i] = FUNC; break;
						}
					}

					stack[j++] = fn + '(' + args.join() + ')';
					curr = curr.caller;
				}
			";
				}
					
                $local_function_body .=	"return stack;
        }
        catch(e)
        {
            
        }";
                $g_javascript_namespace->header_script_generator->add_function_to_main_scope(
                    "getstack","a_e",$local_function_body);
            }
            else
            {
               // echo "g_javascript_namespace ERR";
            }	
        }
		// P
        public function prepare_log($a_log,$a_debug_backtrace,&$a_msg_type,&$a_msg,&$a_url,&$a_lno,&$a_stack)
		{
		  try
		  {
            //echo "prepare_log";
			if (is_object($a_log))
            {
                //echo '<br>method_exists getMessage<br>';
                $a_msg_type = self::msg_type_error;
                $a_msg = "errore exception: ".addslashes($a_log->getMessage);
                $a_url = $a_log->getFile;
                $a_lno = $a_log->getLine;
                $a_stack = $a_log->getTraceAsString;
            }
            else
            {   
                //echo '<br>NOT method_exists getMessage<br>';
                $a_msg_type = self::msg_type_error;
                $a_msg = "errore testo: ".addslashes(substr($a_log,1,200) ) ;
                if (!empty($a_debug_backtrace))
                {
					$a_url = $a_debug_backtrace[0]["file"];
                    $a_lno = $a_debug_backtrace[0]["line"];
                    $a_stack = 'a_debug_backtrace is NOT EMPTY. ';//.substr(print_r($a_debug_backtrace,true),1,10);
                }
				else
                {
                    $a_url = $_SERVER['REQUEST_URI'];
                    $a_lno = 0;
                    $a_stack = 'a_debug_backtrace IS EMPTY.';
                }
            }    
		  }
		  catch(Exception $e)
          {	
			$e->getMessage = "add_log_error Exception: ".$e->getMessage;
			$this->prepare_log($e,null,
                $local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
            $this->send_log_by_email($local_msg_type,$local_msg,$local_url,$local_lno,$local_stack);
		  }
		}
        // R
        function reset_error_count()
        {
            $this->_error_count = 0;
        }
		public function reset_report_log()
		{
            $this->report_log = '';           
        }	
        
    }
?>